# -*- coding: UTF-8 -*-
import imageio
import os, datetime,time
import requests

'''
通过接口获取所有路线数据
'''
ROAD_URL='http://meteo.awit.net.cn:10280/GuiYang_weather_BS/login.do?doLogin'
UN='demo2'
PW='123456'

METEO_URL=ROAD_URL+'&userName='+UN+'&passWord='+PW
#log
# LOG_ADD='/usr/local/tomcat7/webapps/ROOT/logs/meteo_getpic.txt'
LOG_ADD='F:/guiyang_img/meteo_picgif.txt'

#路线数据
roadData = (requests.post(METEO_URL).json())['obj']['roads']

def create_gif(gif_name, path, duration = 0.3,num=6,type='vis'):
    print gif_name+','+path+','
    '''
    生成gif文件，原始图片仅支持png格式
    gif_name ： 字符串，所生成的 gif 文件名，带 .gif 后缀
    path :      需要合成为 gif 的图片所在路径
    duration :  gif 图像时间间隔
    '''
    frames = []
    image_list=[]
    #pngFiles = os.listdir(path)
    pngFiles=[]
    for i in range(num):
        time_name=(datetime.datetime.now()+datetime.timedelta(hours=i)).strftime("%Y%m%d%H")
        pngFiles.append(type+'_'+str(time_name)+'.png')

    for f in pngFiles:
        if f.endswith('png'):
            if os.path.exists(os.path.join(path, f)):
                image_list.append(os.path.join(path, f))

    image_list.sort(key=lambda x: int(x[-14:-4]))
    print(image_list)
    for image_name in image_list:
        try:
            #读取PNG
            frames.append(imageio.imread(image_name))
        except OSError:
            break
    # 保存为 gif
    imageio.mimsave(gif_name, frames, 'GIF', duration = duration)
    with open(LOG_ADD, 'ab') as f:
    		f.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'：Make '+str(gif_name)+' succ!\n')
    return

'''
主函数
'''
def main(roadCode,type ,num):
    # picPath='/mnt/ftp/meteoftp/'
    picPath='F:/guiyang_img/'+roadCode+'/'
    gif_name = picPath + type + '/' + str(num) + '.gif'
    path = picPath + type
    duration = 0.5
    create_gif(gif_name, path, duration,num,type)

'''
获取48小时内的图片
'''
def loadPic(roadCode):
    for i in [6,12,24,48]:
        main(roadCode,'temp',i)
        main(roadCode,'vis',i)
        main(roadCode,'rain',i)
        main(roadCode,'wind',i)
        main(roadCode,'freez',i)

'''
遍历路线获取图片
'''
for road in roadData:
    roadCode=road['road_code']
    loadPic(roadCode)